<template>
<!-- 商家管理 -->
    <div class="order-merchant-manage">
        <CommonNav v-model="nav" color="blue" :navs="navs"></CommonNav>
        <div class="main">
            <div class="header">
                <div class="total">
                    总订单量：{{currencyStatistics.order_number}}个
                </div>
                <ZbSelect v-model="selectedDateType" type="mini" :options="dateTypeOptions" :hasBr="true" default-br="#101010" default-color="#101010" selected-color="#FFFFFF" selected-br="#288DF8" selected-bg="#288DF8" class="nice" />
            </div>
            <SearchBar v-if="nav === 'order'" v-model="tempName" placeholder="搜索购买者" @search="onClickSearch" />
            <div class="picker-box">
                <SelectShop v-if="shopSelectVisible" v-model="selectedShops" :options="shopList" />
                <TimePicker1 @search="onClickTimeSearch" />
            </div>

            <div class="order-wrap" v-if="(nav === 'order' && orderList.length) || (nav === 'prize' && rebateList.length)">
                <block v-if="nav === 'order'">
                    <OrderCard
                        v-for="(orderId, index) in orderList"
                        @resetOrderList="resetOrderList"
                        @showType="showType"
                        :key="index"
                        label-color="blue"
                        :order-key="orderKey"
                        :order="orderMap[orderId]"
                        :final="orderMap[orderId].final_payment"
                        :delivery="orderMap[orderId].delivery"
                        :buyer-confirm="orderMap[orderId].buyer_confirm"
                        :detail="orderMap[orderId].detail"
                        :gift="orderMap[orderId].gift"
                        :is-prepay="orderMap[orderId].is_prepay"
                        :order-id="orderMap[orderId].id"
                        :link-id="orderMap[orderId].link_id"
                        :has-btn="true"
                        :cover="orderMap[orderId].cover"
                        :title="orderMap[orderId].title"
                        :nickname="orderMap[orderId].name ? orderMap[orderId].name : orderMap[orderId].nickname"
                        :price="orderMap[orderId].price"
                        :original-price="orderMap[orderId].original_price"
                        :coupon-pay="orderMap[orderId].coupon_pay"
                        :createdAt="orderMap[orderId].created_at"
                        :referrer="orderMap[orderId].referrer_name ? orderMap[orderId].referrer_name : orderMap[orderId].referrer_nickname"
                        :referrer-level="orderMap[orderId].referrer_level"
                        :referrer-type="orderMap[orderId].referrerType"
                        :is-finish="orderMap[orderId].is_finish"
                        :order-status="orderMap[orderId].status"
                        :order-type="orderMap[orderId].type"
                        :mobile="orderMap[orderId].mobile"
                        :buyer-remark="orderMap[orderId].buyer_remark"
                        :address="orderMap[orderId].address" />
                </block>
                <block v-if="nav === 'prize'">
                    <RebateCard
                        v-for="(rebate, index) in rebateList"
                        :key="index"
                        :nickname="rebate.name ? rebate.name : rebate.nickname"
                        :title="rebate.title"
                        :avatar="rebate.avatar"
                        :shop="rebate.shop"
                        :created-at="rebate.created_at"
                        :price="rebate.price"
                        :referrer="rebate.referrer"
                        :rebate="rebate.rebate"
                        :identity="rebate.identity" />
                </block>
            </div>
            <ListEmpty v-else />
        </div>
    </div>
</template>

<script lang="ts">
import {
    api,
} from '@/lib/api';
import { ROUTE_NAME } from '@/lib/constant';

import store from '@/store';
import CustomNav from '@/components/nav/customNav.vue';
import CommonNav from '@/components/nav/commonNav.vue';
import ZbSelect from '@/components/common/zbSelect.vue';
import OrderCard from '@/features/manage/orderCard.vue';
import RebateCard from '@/features/manage/rebateCard.vue';
import TimePicker1 from '@/features/manage/timePicker1.vue';
import SelectShop from '@/features/manage/select.vue';
import PeopleSelect from '@/features/manage/peopleSelect.vue';
import ListEmpty from '@/components/list/listEmpty.vue';
import {
    currency,
    getOrderKey,
    getRebateKey,
    getFirstDayOfMonth,
    getFirstDayOfSeason,
    getFirstDayOfYear,
    getMapKey,
} from '@/lib/utils';
import { Component, Vue, Watch } from 'vue-property-decorator';
import { EMPTY_LIST } from '@/lib/constant';
import SearchBar from '@/module/manage/components/searchBar.vue';

@Component({
    name: 'OrderMerchantManage',
    components: {
        CustomNav,
        CommonNav,
        ZbSelect,
        OrderCard,
        RebateCard,
        TimePicker1,
        SelectShop,
        PeopleSelect,
        ListEmpty,
        SearchBar,
    },
})
export default class OrderMerchantManage extends Vue {
    public nav: 'order' | 'prize' = 'order';
    public navs: ValueText1[] = [
        { text1: '订单', value: 'order' },
        { text1: '奖励', value: 'prize' },
    ];
    public selectedDateType = '';
    public dateTypeOptions: string[] = [ '月度', '季度', '年度' ];

    // todo: 好像没有什么用
    public pickerTime: any = '全部';

    public selectedShops: number[] = [];
    public nowDate = new Date();
    public startDate: string | null = null;
    public endDate: string | null = null;
    public tempName = '';
    public name = '';
    public rebateKey = '';

    public async showType(_data){
        const res = await store.dispatch('order/getManageOrderDetail', {
            orderId: _data.orderId,
        });
        if (res.statusCode !== 200 || res.data.status !== 0) {
            wx.showToast({
                title: '订单不存在',
                icon: 'none',
            });

        }else{
            if(res.data.data == null){
                wx.showToast({
                    title: '订单不存在',
                    icon: 'none',
                });
            }else{
                api.push({
                    name: ROUTE_NAME.ORDER_MANAGE_ORDER_DETAIL,
                    params: {
                        orderId: _data.orderId+ '',
                    }
                })
            }
        }
    }

    /** 用户基础信息 */
    public get userBasicInfo() {
        return store.state.user.basicInfo;
    }
    public get orderListMap() {
        return store.state.manage.orderListMap;
    }
    public get orderMap() {
        return store.state.manage.orderMap;
    }
    public get rebateListMap() {
        return store.state.manage.rebateListMap;
    }
    public get rebateMap() {
        return store.state.manage.rebateMap;
    }
    public get shopMap() {
        return store.state.shop.shopMap;
    }
    public get shopSelectVisible() {
        const identity = this.userBasicInfo.employee_identity;
        return identity && (identity === '平台管理' || identity === '商家管理');
    }
    /** 店铺列表 */
    public get shopList() {
        const identity = this.userBasicInfo.employee_identity;
        if (!identity) {
            return [];
        }
        const allShopList = store.state.shop.allShopList;
        
        if (identity === '平台管理') {
            return allShopList.map((id) => this.shopMap[id]);
        } else {
            return this.userBasicInfo.shop;
        }
    }
    public get currencyStatistics() {
        return {
            order_number: this.statistics.order_number,
            rebate_number: this.statistics.rebate_number,
            money: currency(this.statistics.money),
        };
    }
    public get shopIdArr() {
        // 有选择的店铺
        if (this.selectedShops && this.selectedShops.length) {
            return this.selectedShops;
        } else {
            // 获取所有店铺
            return [];
        }
    }
    public get orderKey() {
        return getOrderKey({
            name: this.name,
            shopId: this.shopIdArr,
            level: 3,
            start: this.startDate,
            end: this.endDate,
        });
    }
    public get orderList() {
        return this.orderListMap[this.orderKey] ? this.orderListMap[this.orderKey].list : [];
    }
    public get rebateList() {
        const map = store.state.manage.rebateMap;
        const wrap = this.rebateListMap[this.rebateKey] || EMPTY_LIST;
        return wrap.list.map((id) => map[id]);
    }
    public get statisticsData() {
        const params: any = {
            start: this.startDate,
            end: this.endDate,
            shopId: this.shopIdArr,
            userId: null,
        };
        if (this.name && this.nav === 'order') {
            params.name = this.name;
        }
        return params;
    }
    public get statistics() {
        const empty = {
            order_number: '-',
            rebate_number: '-',
            money: '-',
        };
        if (!this.userBasicInfo) {
            return empty;
        }
        const key = getMapKey(this.statisticsData);
        const statistics = store.state.manage.statisticsMap[key];
        return statistics || empty;
    }

    @Watch('selectedShops')
    public onSelectedShopsChange(val: any) {
        this.getList(true);
        this.getStatistics();
    }
    @Watch('nav')
    public onNavChange(val: any) {
        this.getList(true);
    }
    @Watch('rebateKey')
    public onRebateKeyChange(val) {
        // console.log('page rebateKey', val);
    }
    @Watch('orderKey')
    public onOrderKeyChange(val: any) {
        // console.log('page key', val);
    }
    @Watch('selectedDateType')
    public onSelectedDateTypeChange(val: any) {
        if (val === '月度') {
            this.startDate = getFirstDayOfMonth(new Date());
        } else if (val === '季度') {
            this.startDate = getFirstDayOfSeason(new Date());
        } else if (val === '年度') {
            this.startDate = getFirstDayOfYear(new Date());
        }
        this.endDate = null;
        this.getList(true);
        this.getStatistics();
    }
    @Watch('pickerTime')
    public onPickerTimeChange(val: any) {
        if (val === '全部') {
            this.startDate = null;
            this.endDate = null;
        } else {
            this.startDate = val;
            const arr = val.split('-');
            arr[2] = Number(arr[2]) + 1;
            this.endDate = arr.join('-');
        }
        this.getList(true);
        this.getStatistics();
    }

    public async resetOrderList() {
        this.getOrderList(true);
    }
    public onClickTimeSearch(obj) {
        this.startDate = obj.startDate;
        this.endDate = obj.endDate;
        this.getList(true);
    }
    public onClickSearch() {
        this.name = this.tempName;
        this.getStatistics();
        this.getOrderList(true);
    }

    public async getOrderList(forceUpdate: any) {
        const params = {
            offset: this.orderList.length,
            count: 10,
            level: 3,
            start: this.startDate,
            end: this.endDate,
            shopId: this.shopIdArr,
            name: this.name,
        };
        if (forceUpdate) {
            Object.assign(params, {
                offset: 0,
                forceUpdate,
            });
        }
        await store.dispatch('manage/getOrderList', params);
    }

    public async getRebateList(forceUpdate: any) {
        const params = {
            offset: this.rebateList.length,
            count: 10,
            start: this.startDate,
            end: this.endDate,
            shopId: this.shopIdArr,
        };
        if (forceUpdate) {
            Object.assign(params, {
                offset: 0,
                forceUpdate,
            });
        }
        await store.dispatch('manage/getRebateList', params);
    }

    public async getStatistics() {
        store.dispatch('manage/getStatistics', this.statisticsData);
    }
    public async getList(forceUpdate = false) {
        if (this.nav === 'order') {
            this.getOrderList(forceUpdate);
        } else {
            this.rebateKey = getRebateKey({
                start: this.startDate,
                end: this.endDate,
                shopId: this.shopIdArr,
            });
            this.getRebateList(forceUpdate);
        }
    }
    public async onReachBottom() {
        this.getList();
    }

    // 下拉刷新
    async onPullDownRefresh() {
        store.commit('utils/startPulldown');
        const params = {
            offset: 0,
            count: 10,
            level: 3,
            start: this.startDate,
            end: this.endDate,
            shopId: this.shopIdArr,
            name: this.name,
            forceUpdate: true
        };
        await store.dispatch('manage/getOrderList', params);
        const params2 = {
            offset: 0,
            count: 10,
            start: this.startDate,
            end: this.endDate,
            shopId: this.shopIdArr,
            forceUpdate: true
        };
        await store.dispatch('manage/getRebateList', params2);

        store.commit('utils/endPulldown');
    }

    public async created() {
        store.commit('utils/startRequest');
        this.rebateKey = getRebateKey({
            start: this.startDate,
            end: this.endDate,
            shopId: this.shopIdArr,
        });
        await Promise.all([
            this.getStatistics(),
            store.dispatch('shop/getAllShopList'),
        ]);
        store.commit('utils/endRequest');
        this.getList();

        window.addEventListener('wxshow', () => {
            this.getList(true);
        });
        window.addEventListener('reachbottom', this.onReachBottom);
        window.addEventListener('pulldownrefresh', this.onPullDownRefresh);
    }
    public beforeDestroy() {
        window.removeEventListener('reachbottom', this.onReachBottom);
        window.removeEventListener('pulldownrefresh', this.onPullDownRefresh);
    }
}
</script>

<style lang="less" scopd>

@import "../../lib/style/mixins.less";

.nice{
    width: 39%;
    display: flex;
}
.order-merchant-manage {
    min-height: 100%;
    background-color: #f8f8f8;
    .main {
        .header {
            padding: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .select-btn-box {
                .item {
                }
            }
        }
        .order-wrap {
            padding: 0 12rpx;
        }
    }
    .picker-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 14px;
    }
}

</style>
